﻿using Microsoft.Extensions.DependencyInjection;  //引用
using Microsoft.Extensions.Hosting;
using DI.Console;

using IHost host = Host.CreateDefaultBuilder(args).ConfigureServices(srv =>
{
    // ⚠ 注册不同生命周期的服务
    srv.AddSingleton<ISingletonReport, SingletonReport>();     //单例模式
    srv.AddScoped<IScopedReport, ScopedReport>();               //作用域模式
    srv.AddTransient<ITransientReport, TransientReport>();     //瞬态模式
    srv.AddTransient<ServiceCaller>();
}).Build();

// 从容器读取ServiceProvider
Apply(host.Services, "Provider A");
Apply(host.Services, "Provider B");

await host.RunAsync();


/// <summary>
/// 演示不同的生命周期
/// </summary>
static void Apply(IServiceProvider serviceProvider, string lifetime)
{
    //创建服务
    using var scope = serviceProvider.CreateScope();
    IServiceProvider provider = scope.ServiceProvider;

    // 获取服务实例
    ServiceCaller logger = provider.GetRequiredService<ServiceCaller>();
    logger.ReportServiceLifetimeDetails($"{lifetime} => 第 1 次服务请求");


    logger = provider.GetRequiredService<ServiceCaller>();
    logger.ReportServiceLifetimeDetails($"{lifetime} => 第 2 次服务请求");

    Console.WriteLine();
}